import { connect } from '../db'

import { ensureConfigInitialized, serviceUrl } from '../config/config'

export function insert({ modelName, videoPath, audioPath, voiceId }) {
  const db = connect()
  const stmt = db.prepare(
    'INSERT INTO f2f_model (name, video_path, audio_path, voice_id, created_at) VALUES (?, ?, ?, ?, ?)'
  )
  const info = stmt.run(modelName, videoPath, audioPath, voiceId, Date.now())
  return info.lastInsertRowid
}

export function selectPage({ page, pageSize, name = '' }) {
  const db = connect()
  const offset = (page - 1) * pageSize
  return db
    .prepare(
      `SELECT * FROM f2f_model WHERE name like '%${name}%' ORDER BY created_at DESC LIMIT ${pageSize} OFFSET ${offset}`
    )
    .all()
}

export async function listModel(params) {
  // 确保配置初始化完成
  await ensureConfigInitialized();

  const http_url = serviceUrl.baseUrlWithPort

  // 过滤掉值为null、undefined或者"null"字符串的参数
  const filteredParams = {};
  for (const key in params) {
    if (params[key] !== null && params[key] !== undefined && params[key] !== "null") {
      filteredParams[key] = params[key];
    }
  }

  // 构建URL参数
  const searchParams = new URLSearchParams();
  for (const key in filteredParams) {
    searchParams.append(key, filteredParams[key]);
  }

  const response = await fetch(`${http_url}/apis/model/api/model/list?${searchParams.toString()}`, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json'
    }
  });

  // 检查响应状态
  if (!response.ok) {
    throw new Error(`请求失败: ${response.status} ${response.statusText}`);
  }

  const data = await response.json();
  return data;
}

export async function listModel2(params) {
  // 确保配置初始化完成
  await ensureConfigInitialized();

  const http_url = serviceUrl.baseUrlWithPort

  // 与上面相同的过滤逻辑
  const filteredParams = {};
  for (const key in params) {
    if (params[key] !== null && params[key] !== undefined && params[key] !== "null") {
      filteredParams[key] = params[key];
    }
  }

  const searchParams = new URLSearchParams();
  for (const key in filteredParams) {
    searchParams.append(key, filteredParams[key]);
  }

  const response = await fetch(`${http_url}/apis/model/api/model/list?${searchParams.toString()}`, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json'
    }
  });

  // 检查响应状态
  if (!response.ok) {
    throw new Error(`请求失败: ${response.status} ${response.statusText}`);
  }

  const data = await response.json();
  return data;
}

export function count(name = '') {
  const db = connect()
  const rows = db
    .prepare(`SELECT COUNT(*) as total FROM f2f_model WHERE name like '%${name}%'`)
    .get()
  return rows.total
}

export async function updateDigitalHuman(data) {
  // 确保配置初始化完成
  await ensureConfigInitialized();

  const http_url = serviceUrl.baseUrlWithPort

  return fetch(`${http_url}/apis/model/api/model/update`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  })
    .then(response => {
      if (!response.ok) {
        throw new Error(`请求失败: ${response.status} ${response.statusText}`);
      }
      return response.json();
    });
}

export async function deleteHuman(modelId) {
  console.log(`${modelId} deleted`);
  // 确保配置初始化完成
  await ensureConfigInitialized();

  const http_url = serviceUrl.baseUrlWithPort

  return fetch(`${http_url}/apis/model/api/model/delete/${modelId}`, {
    method: 'DELETE',
  })
    .then(response => {
      if (!response.ok) {
        throw new Error(`请求失败: ${response.status} ${response.statusText}`);
      }
      return response.json();
    });
}

export async function countCommon(name = '') {
  // 确保配置初始化完成
  await ensureConfigInitialized();

  const http_url = serviceUrl.baseUrlWithPort

  // 构建URL参数
  const searchParams = new URLSearchParams();
  searchParams.append('name', name);

  // 使用fetch API发送请求
  const response = await fetch(`${http_url}/apis/model/api/model/count_common?${searchParams.toString()}`, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json'
    }
  });

  // 检查响应状态
  if (!response.ok) {
    throw new Error(`请求失败: ${response.status} ${response.statusText}`);
  }

  // 解析JSON响应
  const data = await response.json();
  return data;
}

export function selectByID(id) {
  const db = connect()
  const stmt = db.prepare('SELECT * FROM f2f_model WHERE id = ?')
  return stmt.get(id)
}

export async function selectByIDCommonModel(id) {
  // 确保配置初始化完成
  await ensureConfigInitialized();

  const http_url = serviceUrl.baseUrlWithPort

  // 使用fetch代替request.get
  const response = await fetch(`${http_url}/apis/model/api/model/getDetail/${id}`, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json'
    }
  });

  // 检查响应状态
  if (!response.ok) {
    throw new Error(`请求失败: ${response.status} ${response.statusText}`);
  }

  // 解析JSON响应
  const data = await response.json();
  return data.data;
}

export function remove(id) {
  const db = connect()
  db.prepare(`DELETE FROM f2f_model WHERE id = ?`).run(id)
}
